package com.wnx.job.modules.pms.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnx.job.domain.CascadeNode;
import com.wnx.job.domain.PostTypeNode;
import com.wnx.job.modules.pms.mapper.PmsPostTypeMapper;
import com.wnx.job.modules.pms.model.PmsPostType;
import com.wnx.job.modules.pms.service.PmsPostTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wangnaixing
 * @since 2021-12-17
 */
@Service
public class PmsPostTypeServiceImpl extends ServiceImpl<PmsPostTypeMapper, PmsPostType> implements PmsPostTypeService {
    @Resource
    private PmsPostTypeMapper postTypeMapper;


    /**
     * 获取职位类型树
     * @return
     */
    @Override
    public List<CascadeNode> getPostTypeTree() {
        List<PmsPostType> postTypeList = postTypeMapper.selectList(null);
        //转树状结构
        List<PostTypeNode> result = postTypeList.stream()
                .filter(postType -> postType.getParentId().equals(0L))
                .map(postType -> buildTreePostType(postType, postTypeList))
                .collect(Collectors.toList());



        //实体转DTO,并返回。
        return convert(result);
    }

    /**
     * 将权限转换为带有子级的权限对象
     * 当找不到子级权限的时候map操作不会再递归调用covert
     */
    private PostTypeNode buildTreePostType(PmsPostType dict, List<PmsPostType> dictList) {
        PostTypeNode node = new PostTypeNode();

        BeanUtils.copyProperties(dict, node);
        List<PostTypeNode> children = dictList.stream()
                .filter(subDict -> subDict.getParentId().equals(dict.getId()))
                .map(subPermission -> buildTreePostType(subPermission, dictList))
                .collect(Collectors.toList());
        node.setChildren(children);

        return node;
    }

    //实体转DTO
    private List<CascadeNode> convert(List<PostTypeNode> postTypeTree) {
        //构建一个职位类型的Vo集合
        List<CascadeNode> postTypeVoList = new ArrayList<CascadeNode>();

        //对职位类型集合进行for遍历
        postTypeTree.forEach(p -> {
            //构建职位类型的Vo对象
            CascadeNode vo = new CascadeNode();

            //为职位类型的Vo对象属性赋值
            vo.setLabel(p.getName());
            vo.setValue(p.getId());

            //获取子职位类型集合
            List<PostTypeNode> sonPostTypeList = p.getChildren();

            //判断子职位类型集合长度是否大于0并且不为空？
            if (sonPostTypeList != null && sonPostTypeList.size() > 0) {//是

                // 子节点调用当前方法进行再次转换,并存入vo
                vo.setChildren(convert(sonPostTypeList));
            }

            //将职位类型的Vo，存入职位类型的Vo集合。
            postTypeVoList.add(vo);
        });

        return postTypeVoList;
    }
}
